package zk.weart.system.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import zk.weart.core.response.ResultData;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

/**
 * @Author zjk
 * @Description:
 * @Date 2022/5/11 0:58
 **/

@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultData MethodArgumentNotValidException(MethodArgumentNotValidException e)
            throws JsonProcessingException {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuffer sb = new StringBuffer();
        allErrors.forEach(o -> sb.append(o.getDefaultMessage()).append("; "));
        log.error(e.getMessage(), e);
        return ResultData.fail(sb.toString());
    }


    /**
     * 请求的 URL 参数检验
     *
     * @param e 异常信息
     * @return 返回提示信息
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResultData ConstraintViolationException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> allErrors = e.getConstraintViolations();
        StringBuffer sb = new StringBuffer();
        allErrors.forEach(o -> sb.append(o.getMessage()).append("; "));
        return ResultData.fail(sb.toString());
    }





    @ExceptionHandler(BusException.class)
    public ResultData BusException(BusException e) {

        log.error("全局异常拦截 业务出错",e);
        return new ResultData(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResultData Exception(Exception e) {

        log.error("全局异常拦截 未知异常",e);
        return ResultData.error();
    }



}
